const Router = require('koa-router')
const userController = require('../controller/user')
const multer = require('koa-multer')
const path = require('path')
const fs = require('fs')

//文件上传配置
const storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, 'public/backgrounds/')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})
//加载配置
const upload = multer({ storage: storage })
const router = new Router({
    prefix: '/user'
})

//检测用户名
router.post('/testName', userController.testName)

//用户注册
router.post('/register', userController.create)

//密码登陆
router.post('/login', userController.login)

//获取用户信息
router.post('/getUserInfo', userController.getUserInfo)

//刷新token
router.post('/refreshToken', userController.refreshToken)

//上传用户背景图
router.post('/uploadBackground', upload.single('file'), async(ctx, next) => {
    return ctx.body = {
        code: '0',
        filename: ctx.req.file.filename,
        desc: '图片上传成功~'
    } 
})
//上传用户头像
router.post('/uploadAvatar', async(ctx, next) => {
    var req = ctx.request.body
    var name = req.name
    var imgBase64 = req.img
    var imgData = imgBase64.replace(/^data:image\/\w+;base64,/, '')
    var dataBuffer = Buffer.from(imgData, 'base64')
    var imgName = name + '-' + Date.now() + '.png'
    fs.writeFile('public/avatars/'+imgName, dataBuffer, err => {
        if(err) return 
    })
    return ctx.body = {
        code: '0',
        filename: imgName,
        desc: '图片上传成功~'
    } 
})

module.exports = router
